import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:flutter_learn_vi/src/bean/bean_category.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/utils/date_utils.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';

import '../../account/widget/account_details_widget.dart';
import 'mine_my_integral_item_level_page.dart';
import 'mine_my_rank_item_level_integral_stat_page.dart';
import 'mine_my_score_model.dart';
import 'mine_my_scroe_item_integral_recodel_page.dart';
import 'mine_my_scroe_item_page.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/1/13.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
enum ScoreRankType {
  score, //战绩
  rank, //排行
  integral, //积分
  integralStatistics, //积分统计
  integralStatisticsRecoder, //积分统计 记录
}

///我的积分记录列表页面
class MyScorePage extends StatefulWidget {
  final ScoreRankType scoreRankType;

  MyScorePage({this.scoreRankType = ScoreRankType.score});

  @override
  _MyScorePageState createState() => _MyScorePageState();
}

class _MyScorePageState extends State<MyScorePage>
    with TickerProviderStateMixin {
  List<CategoryBean> _list = [];
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    getMyScoreCategorys();
  }

  @override
  void dispose() {
    dateSelectControler.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: widget.scoreRankType == ScoreRankType.score
          ? Colors.grey[200]
          : Colors.grey[200],

      ///填充布局
      body: NestedScrollView(
        body: buildMainBody(context),
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return [
            SliverAppBar(
              //第一部分 标题 这里是搜索框
              title: Text(buildHeaderText()),
              actions: [buildTopRightActions()],
              bottom: buildTabBar(),
              //标题居中
              centerTitle: true,
              //5.1.2小节中有对这一块的属性配置说明
              pinned: true,
              floating: false,
              snap: false,
              //阴影高度
              elevation: 0.0,
              //展开的高度
              expandedHeight: 255,
              //第二部分 AppBar下的内容区域
              flexibleSpace: FlexibleSpaceBar(
                //背景
                //配置的是一个widget也就是说在这里可以使用任意的
                //Widget组合 在这里直接使用的是一个图片
                background: Column(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    AccountDetailsWidget(tag: "recoder"),
                    SizedBox(
                      height: 45,
                    )
                  ],
                ),
              ),
              //第三部分
            ),
          ];
        },
      ),
    );
  }

  StreamController<String> dateSelectControler = StreamController.broadcast();

  Future<void> _selectDate() async {
    final DateTime date = await DatePicker.showDatePicker(context,
        // 是否展示顶部操作按钮
        showTitleActions: true,
        // 最小时间
        minTime: DateTime(2020, 1, 1),
        // 最大时间
        maxTime: DateTime(2099, 6, 7),
        // change事件
        onChanged: (date) {
      print('change $date');
    },
        // 确定事件
        onConfirm: (date) {
      print('confirm $date');
    },
        // 当前时间
        currentTime: DateTime.now(),
        // 语言
        locale: LocaleType.zh);

    if (date == null) {
      ToastUtils.showToast("日期格式不正常 请重新选择");
      return;
    }
    selectedDate = date;
    String dateStr = ViDateUtils.formatDate(date, format: "yyyy-MM");
    myScoreCurrentSelectDate = dateStr;
    dateSelectControler.add(dateStr);
  }

  buildMainBody(BuildContext context) {
    if (_isLoading) {
      return LoadingWidget();
    }
    if (_tabController == null) {
      return NoDataWidget(
        clickCallBack: () {
          setState(() {
            _isLoading = true;
          });
          getMyScoreCategorys();
        },
      );
    }
    if (widget.scoreRankType == ScoreRankType.integral) {
      return MineMyIntegralItemLevelPage(
        dateSelectStream: dateSelectControler,
      );
    }
    if (_tabBarViewList.isEmpty) {
      return Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          GestureDetector(
            onTap: () {
              setState(() {
                _isLoading = true;
              });
              getMyScoreCategorys();
            },
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Image.asset(
                  "assets/images/2.0x/home_study.png",
                  width: 33,
                ),
                SizedBox(
                  height: 12,
                ),
                Text(
                  "暂无数据",
                  style: TextStyle(color: Colors.grey),
                )
              ],
            ),
          )
        ],
      );
    }
    return TabBarView(
      children: _tabBarViewList,
      controller: _tabController,
    );
  }

  Future<bool> getMyScoreCategorys() async {
    if (widget.scoreRankType == ScoreRankType.integralStatistics ||
        widget.scoreRankType == ScoreRankType.integralStatisticsRecoder) {
      ResponseInfo responseInfo = await DioUtils.instance.getRequest(
        url: HttpHelper.integralStatistics,
      );

      if (responseInfo.success) {
        _list = [];
        List list = responseInfo.data;
        list.forEach((element) {
          CategoryBean newsBean = CategoryBean.fromJson2(element);
          _list.add(newsBean);
        });
      }
      _isLoading = false;
      initTabFunction();
    } else {
      //post请求发送
      ResponseInfo responseInfo = await DioUtils.instance.getRequest(
        url: HttpHelper.categorys,
      );

      if (responseInfo.success) {
        _list = [];
        List list = responseInfo.data;
        list.forEach((element) {
          CategoryBean newsBean = CategoryBean.fromJson(element);
          _list.add(newsBean);
        });
      }
      _isLoading = false;
      initTabFunction();
    }
    return Future.value(true);
  }

  TabController _tabController;
  List<Tab> _tabList = [];
  List<Widget> _tabBarViewList = [];

  void initTabFunction() {
    _tabController = new TabController(vsync: this, length: _list.length);
    _list.forEach((element) {
      _tabList.add(Tab(
        text: "${element.categoryName}",
      ));
      if (widget.scoreRankType == ScoreRankType.integralStatistics) {
        _tabBarViewList.add(
          MineMyRahkIntegralItemLevelPage(
              configId: element.categoryCode,
              dateSelectStream: dateSelectControler),
        );
      } else if (widget.scoreRankType ==
          ScoreRankType.integralStatisticsRecoder) {
        _tabBarViewList.add(
          MineMyScoreIntegralRecoderItemPage(
              configId: element.categoryCode,
              dateSelectStream: dateSelectControler),
        );
      } else {
        _tabBarViewList.add(
          MineMyScoreItemPage(
              scoreRankType: widget.scoreRankType,
              categoryBean: element,
              dateSelectStream: dateSelectControler),
        );
      }
    });
    Future.delayed(Duration.zero, () {
      setState(() {});
    });
  }

  String buildHeaderText() {
    if (widget.scoreRankType == ScoreRankType.score) {
      return "我的积分记录";
    }
    if (widget.scoreRankType == ScoreRankType.rank) {
      return "答题排行榜";
    }
    if (widget.scoreRankType == ScoreRankType.integralStatistics) {
      return "积分排行榜";
    }
    if (widget.scoreRankType == ScoreRankType.integralStatisticsRecoder) {
      return "我的积分记录";
    }
    return "积分排行榜";
  }

  buildTabBar() {
    if (_tabController == null ||
        widget.scoreRankType == ScoreRankType.integral) {
      return null;
    }

    return TabBar(
      isScrollable: true,
      controller: _tabController,
      tabs: _tabList,
    );
  }

  buildTopRightActions() {
    if (widget.scoreRankType == ScoreRankType.integralStatistics ||
        widget.scoreRankType == ScoreRankType.integralStatisticsRecoder) {
      return SizedBox();
    }
    return InkWell(
      onTap: () {
        _selectDate();
      },
      child: Stack(
        alignment: Alignment.center,
        children: [
          Container(
            width: 80,
            padding: EdgeInsets.only(left: 4),
            margin: EdgeInsets.only(right: 12),
            height: 26,
            decoration: BoxDecoration(
                border: Border.all(
                  color: Colors.red,
                ),
                borderRadius: BorderRadius.all(Radius.circular(4))),
            child: Stack(
              alignment: Alignment.center,
              children: [
                // Positioned(
                //   left: 0,
                //   child: Image.asset(
                //     "assets/images/2.0x/book_tips.gif",
                //     width: 42,
                //   ),
                // ),
                Positioned(
                  right: 12,
                  child: Container(
                    child: StreamBuilder<String>(
                      stream: dateSelectControler.stream,
                      initialData: ViDateUtils.formatDate(selectedDate,
                          format: "yyyy-MM"),
                      builder: (BuildContext context,
                          AsyncSnapshot<dynamic> snapshot) {
                        return Text(
                          "${snapshot.data}",
                          style: TextStyle(color: Colors.black),
                        );
                      },
                    ),
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }
}
